using GroupSix.Application.Dtos;
using GroupSix.Application.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using GroupSix.Api.Attributes;

namespace GroupSix.Api.Controllers;

/// <summary>
/// 文章管理控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
// [RequirePermission("article")] // 暂时注释掉权限验证，用于测试
public class ArticleController : ControllerBase
{
    private readonly ArticleService _articleService;
    private readonly ILogger<ArticleController> _logger;

    public ArticleController(ArticleService articleService, ILogger<ArticleController> logger)
    {
        _articleService = articleService;
        _logger = logger;
    }

    /// <summary>
    /// 获取文章列表
    /// </summary>
    /// <param name="query">查询条件</param>
    /// <returns>文章列表</returns>
    [HttpGet("list")]
    public async Task<IActionResult> GetArticles([FromQuery] ArticleQueryDto query)
    {
        try
        {
            var result = await _articleService.GetArticlesAsync(query);
            return Ok(new { success = true, data = result, message = "获取文章列表成功" });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取文章列表失败");
            return StatusCode(500, new { success = false, message = "获取文章列表失败" });
        }
    }

    /// <summary>
    /// 获取文章分类列表
    /// </summary>
    /// <returns>分类列表</returns>
    [HttpGet("categories")]
    public async Task<IActionResult> GetCategories()
    {
        try
        {
            var result = await _articleService.GetCategoriesAsync();
            return Ok(new { success = true, data = result, message = "获取分类列表成功" });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取分类列表失败");
            return StatusCode(500, new { success = false, message = "获取分类列表失败" });
        }
    }

    /// <summary>
    /// 根据ID获取文章详情
    /// </summary>
    /// <param name="id">文章ID</param>
    /// <returns>文章详情</returns>
    [HttpGet("{id}")]
    public async Task<IActionResult> GetArticleById(Guid id)
    {
        try
        {
            var result = await _articleService.GetArticleByIdAsync(id);
            if (result != null)
            {
                return Ok(new { success = true, data = result, message = "获取文章详情成功" });
            }
            else
            {
                return NotFound(new { success = false, message = "文章不存在" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取文章详情失败: {Id}", id);
            return StatusCode(500, new { success = false, message = "获取文章详情失败" });
        }
    }

    /// <summary>
    /// 创建文章
    /// </summary>
    /// <param name="request">创建请求</param>
    /// <returns>创建结果</returns>
    [HttpPost("create")]
    public async Task<IActionResult> CreateArticle([FromBody] CreateArticleRequestDto request)
    {
        try
        {
            var result = await _articleService.CreateArticleAsync(request);
            if (result)
            {
                return Ok(new { success = true, message = "文章创建成功" });
            }
            else
            {
                return BadRequest(new { success = false, message = "文章创建失败" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建文章失败");
            return StatusCode(500, new { success = false, message = "创建文章失败" });
        }
    }

    /// <summary>
    /// 更新文章
    /// </summary>
    /// <param name="id">文章ID</param>
    /// <param name="request">更新请求</param>
    /// <returns>更新结果</returns>
    [HttpPut("{id}")]
    public async Task<IActionResult> UpdateArticle(Guid id, [FromBody] UpdateArticleRequestDto request)
    {
        try
        {
            var result = await _articleService.UpdateArticleAsync(id, request);
            if (result)
            {
                return Ok(new { success = true, message = "文章更新成功" });
            }
            else
            {
                return BadRequest(new { success = false, message = "文章更新失败" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新文章失败: {Id}", id);
            return StatusCode(500, new { success = false, message = "更新文章失败" });
        }
    }

    /// <summary>
    /// 删除文章
    /// </summary>
    /// <param name="id">文章ID</param>
    /// <returns>删除结果</returns>
    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteArticle(Guid id)
    {
        try
        {
            var result = await _articleService.DeleteArticleAsync(id);
            if (result)
            {
                return Ok(new { success = true, message = "文章删除成功" });
            }
            else
            {
                return BadRequest(new { success = false, message = "文章删除失败" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除文章失败: {Id}", id);
            return StatusCode(500, new { success = false, message = "删除文章失败" });
        }
    }

    /// <summary>
    /// 批量删除文章
    /// </summary>
    /// <param name="request">批量删除请求</param>
    /// <returns>删除结果</returns>
    [HttpPost("batch-delete")]
    public async Task<IActionResult> BatchDeleteArticles([FromBody] BatchDeleteRequestDto request)
    {
        try
        {
            var result = await _articleService.BatchDeleteArticlesAsync(request.Ids);
            return Ok(new { success = true, message = $"成功删除 {result} 篇文章" });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "批量删除文章失败");
            return StatusCode(500, new { success = false, message = "批量删除文章失败" });
        }
    }

    /// <summary>
    /// 发布文章
    /// </summary>
    /// <param name="id">文章ID</param>
    /// <returns>发布结果</returns>
    [HttpPost("{id}/publish")]
    public async Task<IActionResult> PublishArticle(Guid id)
    {
        try
        {
            var result = await _articleService.PublishArticleAsync(id);
            if (result)
            {
                return Ok(new { success = true, message = "文章发布成功" });
            }
            else
            {
                return BadRequest(new { success = false, message = "文章发布失败" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "发布文章失败: {Id}", id);
            return StatusCode(500, new { success = false, message = "发布文章失败" });
        }
    }

    /// <summary>
    /// 下线文章
    /// </summary>
    /// <param name="id">文章ID</param>
    /// <returns>下线结果</returns>
    [HttpPost("{id}/offline")]
    public async Task<IActionResult> OfflineArticle(Guid id)
    {
        try
        {
            var result = await _articleService.OfflineArticleAsync(id);
            if (result)
            {
                return Ok(new { success = true, message = "文章下线成功" });
            }
            else
            {
                return BadRequest(new { success = false, message = "文章下线失败" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "下线文章失败: {Id}", id);
            return StatusCode(500, new { success = false, message = "下线文章失败" });
        }
    }

    /// <summary>
    /// 设置文章置顶状态
    /// </summary>
    /// <param name="id">文章ID</param>
    /// <param name="isTop">是否置顶</param>
    /// <returns>设置结果</returns>
    [HttpPost("{id}/top")]
    public async Task<IActionResult> SetArticleTopStatus(Guid id, [FromQuery] bool isTop)
    {
        try
        {
            var result = await _articleService.SetArticleTopStatusAsync(id, isTop);
            if (result)
            {
                return Ok(new { success = true, message = isTop ? "文章置顶成功" : "取消置顶成功" });
            }
            else
            {
                return BadRequest(new { success = false, message = "设置置顶状态失败" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "设置文章置顶状态失败: {Id}, {IsTop}", id, isTop);
            return StatusCode(500, new { success = false, message = "设置置顶状态失败" });
        }
    }

    /// <summary>
    /// 设置文章推荐状态
    /// </summary>
    /// <param name="id">文章ID</param>
    /// <param name="isRecommend">是否推荐</param>
    /// <returns>设置结果</returns>
    [HttpPost("{id}/recommend")]
    public async Task<IActionResult> SetArticleRecommendStatus(Guid id, [FromQuery] bool isRecommend)
    {
        try
        {
            var result = await _articleService.SetArticleRecommendStatusAsync(id, isRecommend);
            if (result)
            {
                return Ok(new { success = true, message = isRecommend ? "文章推荐成功" : "取消推荐成功" });
            }
            else
            {
                return BadRequest(new { success = false, message = "设置推荐状态失败" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "设置文章推荐状态失败: {Id}, {IsRecommend}", id, isRecommend);
            return StatusCode(500, new { success = false, message = "设置推荐状态失败" });
        }
    }

    /// <summary>
    /// 获取文章统计信息
    /// </summary>
    /// <returns>统计信息</returns>
    [HttpGet("statistics")]
    public async Task<IActionResult> GetArticleStatistics()
    {
        try
        {
            var result = await _articleService.GetArticleStatisticsAsync();
            return Ok(new { success = true, data = result, message = "获取文章统计信息成功" });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取文章统计信息失败");
            return StatusCode(500, new { success = false, message = "获取文章统计信息失败" });
        }
    }

    /// <summary>
    /// 增加文章阅读量
    /// </summary>
    /// <param name="id">文章ID</param>
    /// <returns>操作结果</returns>
    [HttpPost("{id}/increment-view")]
    public async Task<IActionResult> IncrementArticleViewCount(Guid id)
    {
        try
        {
            var result = await _articleService.IncrementArticleViewCountAsync(id);
            if (result)
            {
                return Ok(new { success = true, message = "阅读量增加成功" });
            }
            else
            {
                return BadRequest(new { success = false, message = "增加阅读量失败" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "增加文章阅读量失败: {Id}", id);
            return StatusCode(500, new { success = false, message = "增加阅读量失败" });
        }
    }

    /// <summary>
    /// 增加文章点赞数
    /// </summary>
    /// <param name="id">文章ID</param>
    /// <returns>操作结果</returns>
    [HttpPost("{id}/like")]
    public async Task<IActionResult> LikeArticle(Guid id)
    {
        try
        {
            var result = await _articleService.LikeArticleAsync(id);
            if (result)
            {
                return Ok(new { success = true, message = "点赞成功" });
            }
            else
            {
                return BadRequest(new { success = false, message = "点赞失败" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "文章点赞失败: {Id}", id);
            return StatusCode(500, new { success = false, message = "点赞失败" });
        }
    }

    /// <summary>
    /// 取消文章点赞
    /// </summary>
    /// <param name="id">文章ID</param>
    /// <returns>操作结果</returns>
    [HttpPost("{id}/unlike")]
    public async Task<IActionResult> UnlikeArticle(Guid id)
    {
        try
        {
            var result = await _articleService.UnlikeArticleAsync(id);
            if (result)
            {
                return Ok(new { success = true, message = "取消点赞成功" });
            }
            else
            {
                return BadRequest(new { success = false, message = "取消点赞失败" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "取消文章点赞失败: {Id}", id);
            return StatusCode(500, new { success = false, message = "取消点赞失败" });
        }
    }
} 